package com.xhs.exception;

import com.xhs.message.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @desc:
 * @projectName: java-tools-parent
 * @author: xhs
 * @date: 2023-8-19 019 18:52
 * @version: JDK 1.8
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 全局异常拦截（拦截项目中的所有异常）
     *
     * @param e 异常
     * @return ReturnResult
     */
    @ResponseBody
    @ExceptionHandler
    public ReturnResult<Object> handlerException(Exception e) {
        // 如果是通用业务异常，直接返回给前端
        if (e instanceof CommonException) {
            CommonException ee = (CommonException) e;
            log.error("通用业务异常:", ee);
            return ReturnResult.error(ee.getCode(), ee.getMsg());
        } else {
            log.error("全局异常:", e);
            return ReturnResult.error();
        }
    }
}
